#include "httpmgr.h"



HttpMgr::HttpMgr()
{
    // 连接http完成的响应函数
    connect(this, &HttpMgr::SignalHttpFinish, this, &HttpMgr::SlotHttpFinish);

}

HttpMgr::~HttpMgr()
{

}

void HttpMgr::PostHttpReq(QUrl url, QJsonObject json, ReqId req_id, Modules mod)
{
    QByteArray data = QJsonDocument(json).toJson();

    // 设置请求头，设置参数数据为json格式，参数长度
    QNetworkRequest request(url);
    request.setHeader(QNetworkRequest::ContentTypeHeader, "application/json");
    request.setHeader(QNetworkRequest::ContentLengthHeader, QByteArray::number(data.length()));

    // 通过shared_from_this获取指向自己的智能指针
    auto self = shared_from_this();

    // 发送post请求
    QNetworkReply* reply = _manager.post(request, data);

    // 异步处理请求回调
    QObject::connect(reply, &QNetworkReply::finished, [self, reply, req_id, mod](){
        // 处理错误情况
        if (reply->error() != QNetworkReply::NoError) {
            qDebug() << reply->errorString();
            // 发送信号通知完成
            emit self->SignalHttpFinish(req_id, "", ErrorCodes::ERR_NETWORK, mod);
            reply->deleteLater();
            return;
        }

        // 无错误
        QString res = reply->readAll();
        // 发送完成信号
        emit self->SignalHttpFinish(req_id, res, ErrorCodes::SUCCESS, mod);
        reply->deleteLater();
        return;
    });
}

void HttpMgr::SlotHttpFinish(ReqId id, QString res, ErrorCodes err, Modules mod)
{
    // 注册模块
    if (mod == Modules::REGISTERMOD) {
        emit SignalRegModFinish(id, res, err);
    }
}

